# coding: utf-8

import time,sys,os
sys.path.append(os.getcwd())
sys.path.append(os.getcwd()+'/../')

from HPSocket import TcpPack
import HPSocket.pyhpsocket as HPSocket
from HPTcpPack.Pack import Pack

class Server(TcpPack.HP_TcpPackServer):
    EventDescription = TcpPack.HP_TcpPackServer.EventDescription

    def __init__(self,host='127.0.0.1', port=7889, head_flag=0x169,size=0x3FFFFF):
        super().__init__()

        self.host = host
        self.port = port
        self.head_flag = head_flag
        self.size = size

        self.close = True
        self.Pack = Pack()

        pass

    def start(self):
        return self.Start(host=self.host, port=self.port, head_flag=self.head_flag, size=self.size)

    def IfClose(self):
        return self.close

    @EventDescription
    def OnAccept(self, Sender, ConnID, Client):
        (ip,port) = HPSocket.HP_Server_GetRemoteAddress(Sender=Sender, ConnID=ConnID)
        print('[%d, 客户进入] < %s' % (ConnID, (ip, port)))
        return HPSocket.EnHandleResult.HR_OK

    @EventDescription
    def OnSend(self, Sender, ConnID, Data):
        print('[%d, 数据发送] > %s' % (ConnID, repr(Data)))
        return HPSocket.EnHandleResult.HR_OK

    def _OnReceive(self, Sender, ConnID, Data):
        print('[%d, 数据到达]' % (Sender), Data.decode(errors="replace"))
        return HPSocket.EnHandleResult.HR_OK


    @EventDescription
    def OnReceive(self, Sender, ConnID, Data):
        header, resdata = self.Pack.pack_unpack(Data)
        if (header.pack_count == 1):
            return self._OnReceive(Sender, ConnID, resdata)
        else:
            if (header.pack_index < header.pack_count):
                self.Pack.receive_data.append({
                    "index": header.pack_index,
                    "flag": header.flag,
                    "data": resdata
                })
            else:
                fulldata = self.Pack.get_receive_data(header)
                if (fulldata):
                    fulldata = fulldata + resdata
                    return self._OnReceive(Sender, ConnID, fulldata)
                else:
                    print("数据解析失败")
        return HPSocket.EnHandleResult.HR_OK

    def OnClose(self, Sender, ConnID, Operation, ErrorCode):
        (ip, port) = HPSocket.HP_Server_GetRemoteAddress(Sender=Sender, ConnID=ConnID)
        print('[%d, 客户断开] > %s opt=%d err=%d' % (ConnID, (ip, port), Operation, ErrorCode))
        return HPSocket.EnHandleResult.HR_OK


    @EventDescription
    def OnShutdown(self,Sender):
        self.close = True
        return HPSocket.EnHandleResult.HR_OK

    @EventDescription
    def OnPrepareListen(self, Sender, SocketHandler):
        print("开始监听:Sender:%d"%(Sender))
        self.close = False
        return HPSocket.EnHandleResult.HR_OK

    def sendBytes(self,ConnID,Buffer:bytes):
        '''
        发送字节集信息
        :param ConnID: 客户端ID
        :param Buffer:
        :return:
        '''
        msg_list = self.Pack.pack_uppack(max_pack=self.size, Buffer=Buffer)
        print("数据包数量", len(msg_list))
        send = True
        for item in msg_list:
            if self.Send(Sender=self.Server, ConnID=ConnID, Data=item) == False:
                send = False
                break
        return send

    def sendMsg(self,ConnID,Msg:str):
        '''
        发送文本信息
        :param ConnID: 客户端ID
        :param Msg:
        :return:
        '''
        return self.sendBytes(ConnID=ConnID,Buffer=Msg.encode())


if __name__ == '__main__':
    svr = Server(host='127.0.0.1', port=7889, head_flag=0x169,size=0xFF)
    svr.start()

    MSG = '''2023年5月24日至25日，中不边界问题专家组第十二次会议在不丹廷布举行。中方代表团由中国外交部边界与海洋事务司司长洪亮率领，
        不方代表团由不丹国际边界事务秘书长雷多·唐比率领。
        双方回顾了在中国昆明举行的专家组第十一次会议达成的积极共识，并就落实《关于加快中不边界谈判“三步走”路线图的谅解备忘录》进行了坦
        诚和建设性讨论。双方对专家组第十二次会议就落实“三步走”路线图取得的进展表示满意。
        '''

    while svr.IfClose()==False:

        time.sleep(1)
    print("结束")